package com.LeeCode;

/**
 * 分隔链表
 */

public class Code725 {
    public static void main(String[] args) {
        int[] nums = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        int k = 3;
        ListNode head = Utils.arrayToListNode(nums);
        new Code725().splitListToParts(head, k);
    }

    public ListNode[] splitListToParts(ListNode head, int k) {
        ListNode cur = head;
        int count = 0;
        while (cur != null) {
            count++;
            cur = cur.next;
        }
        int base = count / k, remainder = count % k;
        ListNode[] res = new ListNode[k];

        ListNode dummy = new ListNode(0, head), prev = dummy;
        cur = head;

        for (int i = 0; i < k; i++) {
            for (int index = 0; index < base; index++) {
                if (index == 0)
                    res[i] = cur;
                prev = prev.next;
                cur = cur.next;
            }
            if (remainder > 0) {
                if (res[i] == null)
                    res[i] = cur;
                cur = cur.next;
                prev = prev.next;
                remainder--;
            }
            prev.next = null;
            dummy.next = cur;
            prev = dummy;
        }
        return res;
    }
}
